const CryptoJS = require('crypto-js');
const chance = require('chance')();
const {URL} = require('url');

class Utils {
  // aes 加密
  encrypt(word, secret) {
    const key = CryptoJS.enc.Utf8.parse(secret);
    const iv = key;
    const srcs = CryptoJS.enc.Utf8.parse(word);
    const encrypted = CryptoJS.AES.encrypt(srcs, key, {iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7});
    return encrypted.ciphertext.toString(CryptoJS.enc.Base64);
  }

  // aes 解密
  decrypt(txt, secret) {
    const key = CryptoJS.enc.Utf8.parse(secret);
    const iv = key;
    const bytes = CryptoJS.AES.decrypt(txt, key, {iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7});
    const plaintext = bytes.toString(CryptoJS.enc.Utf8);
    return plaintext;
  }

  // 生成token
  generateToken(txt, secret) {
    txt += Date.now();
    return CryptoJS.HmacMD5(txt, secret).toString(CryptoJS.enc.Hex);
  }

  // md5
  md5(txt) {
    return CryptoJS.MD5(txt).toString(CryptoJS.enc.Hex);
  }

  // url params 拼接 ? &
  concat(url, _id) {
    if (url == '' || typeof url === 'undefined') {
      return '';
    }
    if (url.indexOf('?') === -1) {
      return url + '?id=' + _id;
    }
    const lastChar = url.charAt(url.length - 1);
    switch (lastChar) {
      case '?':
        return url + 'id=' + _id;
      case '&':
        return url + 'id=' + _id;
      default:
        return url + '&id=' + _id;
    }
  }

  luck(array, rate, num) {
    let random = []
    for (let i = 1; i <= num; i++) {
      random.push(chance.weighted(array, rate))
    }
    return random
  }

  mtaSign(params, secretKey) {
    // 排序
    const keys = Object.keys(params);
    keys.sort();

    // 拼接至secret_key后，以 key=value 方式拼接
    let str = secretKey;
    keys.map(item => {
      str = str + item + '=' + params[item];
    })
    return this.md5(str);
  }

  /**
   * array2 比 array1 共有的，新增的，缺少的key值部分
   */
  mix(array1, array2, key) {

    const array1Set = new Set(),
      array2Set = new Set();

    array1.map(v => {
      array1Set.add(v[key].toString());
    });
    array2.map(v => {
      array2Set.add(v[key].toString());
    });

    return {
      update: array2.filter(v => {
        return array1Set.has(v[key].toString());
      }),
      add: array2.filter(v => {
        return !array1Set.has(v[key].toString());
      }),
      del: array1.filter(v => {
        return !array2Set.has(v[key].toString());
      }),
    };
  }

  /**
   * 取消hrrf 的origin与search
   * @param url
   * @returns {string}
   */
  baseUrl(href) {
    if (!href) {
      return href;
    }
    const url = new URL(href);
    const result = url.host + url.pathname;
    return result.toLowerCase();
  }
}

module.exports = new Utils();
